package com.ruoyi.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.constant.UserConstants;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.domain.SysDept;
import com.ruoyi.system.api.domain.SysUser;
import com.ruoyi.system.mapper.DeptMapper;
import com.ruoyi.system.service.DeptService;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class DeptServiceImpl extends ServiceImpl<DeptMapper, SysDept> implements DeptService {

    @Override
    public List<SysDept> selectDeptList(SysDept dept) {
        LambdaQueryWrapper<SysDept> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysDept::getDelFlag,"0");
        if (null!=dept.getDeptId()){
            wrapper.eq(SysDept::getDeptId,dept.getDeptId());
        }
        if (null!=dept.getParentId()){
            wrapper.eq(SysDept::getParentId,dept.getParentId());
        }
        if (null!=dept.getDeptName() && !dept.getDeptName().equals("")){
            wrapper.like(SysDept::getDeptName,dept.getDeptName());
        }
        if (null!=dept.getStatus() && !dept.getStatus().equals("")){
            wrapper.eq(SysDept::getStatus,dept.getStatus());
        }
        wrapper.orderByAsc(SysDept::getParentId,SysDept::getOrderNum);
        return baseMapper.selectList(wrapper);
    }

    @Override
    public void checkDeptDataScope(Long deptId) {
        if (!SysUser.isAdmin(SecurityUtils.getUserId()) && StringUtils.isNotNull(deptId)){
            SysDept dept = baseMapper.selectById(deptId);
            if (StringUtils.isNotNull(dept)) {
                throw new ServiceException("没有权限访问部门数据！");
            }
        }
    }

    @Override
    public boolean checkDeptNameUnique(SysDept dept) {
        Long deptId = StringUtils.isNull(dept.getDeptId()) ? -1L : dept.getDeptId();
        SysDept info = baseMapper.selectOne(Wrappers.<SysDept>lambdaQuery().eq(SysDept::getDeptName,dept.getDeptName()).eq(SysDept::getParentId,dept.getParentId()).eq(SysDept::getDelFlag,"0"));
        if (StringUtils.isNotNull(info) && info.getDeptId().longValue() != deptId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    @Override
    public int selectNormalChildrenDeptById(Long deptId) {
        Long l = baseMapper.selectCount(Wrappers.<SysDept>lambdaQuery().eq(SysDept::getStatus, "0").eq(SysDept::getDelFlag,"0").like(SysDept::getAncestors,deptId));
        return l.intValue();
    }

    @Override
    public int updateDept(SysDept dept) {
        SysDept newParentDept = baseMapper.selectById(dept.getParentId());
        SysDept oldDept = baseMapper.selectById(dept.getDeptId());
        if (StringUtils.isNotNull(newParentDept) && StringUtils.isNotNull(oldDept)) {
            String newAncestors = newParentDept.getAncestors() + "," + newParentDept.getDeptId();
            String oldAncestors = oldDept.getAncestors();
            dept.setAncestors(newAncestors);
            updateDeptChildren(dept.getDeptId(), newAncestors, oldAncestors);
        }
        int result = baseMapper.updateById(dept);
        if (UserConstants.DEPT_NORMAL.equals(dept.getStatus()) && StringUtils.isNotEmpty(dept.getAncestors())
                && !StringUtils.equals("0", dept.getAncestors()))
        {
            // 如果该部门是启用状态，则启用该部门的所有上级部门
            updateParentDeptStatusNormal(dept);
        }
        return result;
    }

    private void updateParentDeptStatusNormal(SysDept dept) {
        String ancestors = dept.getAncestors();
        Long[] deptIds = Convert.toLongArray(ancestors);
        SysDept sysDept = new SysDept();
        sysDept.setStatus("0");
        baseMapper.update(sysDept,Wrappers.<SysDept>lambdaUpdate().set(SysDept::getStatus,"0").in(SysDept::getDeptId,deptIds));
    }

    /**
     * 修改子元素关系
     *
     * @param deptId 被修改的部门ID
     * @param newAncestors 新的父ID集合
     * @param oldAncestors 旧的父ID集合
     */
    public void updateDeptChildren(Long deptId, String newAncestors, String oldAncestors)
    {
        List<SysDept> children = baseMapper.selectList(Wrappers.<SysDept>lambdaQuery().like(SysDept::getAncestors,deptId));
        for (SysDept child : children) {
            child.setAncestors(child.getAncestors().replaceFirst(oldAncestors, newAncestors));
        }
        if (children.size() > 0) {
            baseMapper.updateDeptChildren(children);
        }
    }
}
